/*
 * @(#)MaintOptionsSetupAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.setup.web;

import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.setup.SetupOptionFactory;
import com.dcivision.setup.bean.SetupOption;
import com.dcivision.setup.dao.AbstractSetupOptionDAObject;
import com.dcivision.setup.dao.SetupOptionDocumentRelationshipDAObject;

/**
 *  MaintAction Handler
 *
 *  @author           Kennedy Lam
 *  @company          DCIVision Limited
 *  @creation date    28/07/2003
 *  @version          $Revision: 1.6.2.2 $
 */
public class MaintOptionsSetupAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.6.2.2 $";


  /**
   *
   */
  public MaintOptionsSetupAction() {
    super();
  }

  /**
   * getFunctionCode
   *
   * @return The corresponding system function code of action
   */
  
  public String getFunctionCode() {
    return SystemFunctionConstant.SETUP_OPTION_SETUP;
  }


  /**
  * Irrelevant overridden method.
  * Use getMajorDAObject(HttpServletRequest) instead.
  *
  * @see com.dcivision.framework.web.AbstractAction#getMajorDAOClassName()
  * @see com.dcivision.setup.web.MaintOptionsSetupAction#getMajorDAObject(HttpServletRequest)
  */
  
  public String getMajorDAOClassName() {
    return "com.dcivision.setup.dao.SetupOptionCountryDAObject";
  }

  /**
   * Overridden method
   *
   * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  
  public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws ServletException {

    //log.debug("DEBUG - MaintOptionsSetupAction.execute()");

    super.execute(mapping, form, request, response);
    //log.debug("DEBUG - Reset and calling mapping.findForward()");
    MaintOptionsSetupForm maintForm = (MaintOptionsSetupForm) form;

    maintForm.reset(mapping, request);
    maintForm.setOpMode(null);  // force it to reload the page
    maintForm.setNavMode(null); // after each form action

    return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
  }

  /* (non-Javadoc)
   * @see com.dcivision.framework.web.AbstractMaintAction#updateRecord(org.apache.struts.action.ActionMapping, com.dcivision.framework.web.AbstractActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws ApplicationException {

    //super.updateRecord(mapping, form, request, response);
    //log.debug("DEBUG - com.dcivision.setup.dao.MaintOptionSetupAction.updateRecord()");

    AbstractDAObject obj = getMajorDAObject(request);

    try {
      AbstractSetupOptionDAObject setupOptionDAO = (AbstractSetupOptionDAObject) obj;
      SetupOption setupOption = (SetupOption) setupOptionDAO.updateObject(form.getFormData());

      //maintForm.reset(mapping, request);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
    }
  }


  /* (non-Javadoc)
   * @see com.dcivision.framework.web.AbstractMaintAction#insertRecord(org.apache.struts.action.ActionMapping, com.dcivision.framework.web.AbstractActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws ApplicationException {

    //super.insertRecord(mapping, form, request, response);
    //log.debug("DEBUG - com.dcivision.setup.dao.MaintOptionSetupAction.insertRecord()");

    AbstractDAObject obj = getMajorDAObject(request);

    try {
      AbstractSetupOptionDAObject setupOptionDAO = (AbstractSetupOptionDAObject) obj;
      /*
       * Update Code Start
       * Author			Jim.Zhou
       * Date			2006/04/21
       * Bug			#4298
       */
      this.initDB(mapping,form,request,response);
      /*
       * Update Code End
       */
      SetupOption setupOption = (SetupOption) setupOptionDAO.insertObject(form.getFormData());

      //maintForm.reset(mapping, request);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
    }
    return;
  }
  /*
   * Update Code Start
   * Author			Jim.Zhou
   * Date			2006/04/21
   * Bug			#4298
   */
  private void initDB(ActionMapping mapping, AbstractActionForm form,HttpServletRequest request, HttpServletResponse response)throws ApplicationException {
    AbstractSetupOptionDAObject setupOptionDAO = (AbstractSetupOptionDAObject) this.getMajorDAObject(request);
    String tableName = setupOptionDAO.getTableName();
    Connection dbConn = null;
    java.sql.PreparedStatement preStat = null;
    boolean noTableMatchFlag = false;
    java.sql.ResultSet rs = null;
    java.sql.PreparedStatement preStat1 = null;
    java.sql.ResultSet rs1 = null;
    java.sql.PreparedStatement preStat2 = null;
    try {
      dbConn = DataSourceFactory.getConnection();
      preStat = dbConn.prepareStatement("SELECT TABLE_KEY_MAX FROM SYS_TABLE_KEY WHERE TABLE_NAME=?");
        preStat.setString(1, tableName);
        rs = preStat.executeQuery();
          if (rs.next()) {
          } else {
              // No Table Matched.
              preStat1 = dbConn.prepareStatement("SELECT MAX(ID) FROM " + tableName);
            rs1 = preStat1.executeQuery();
            if (rs1.next()){
              int maxId = rs1.getInt(1);
              while (rs1.next()){
                if (maxId < rs1.getInt(1)){
                  maxId = rs1.getInt(1);
                }
              }
                preStat2 = dbConn.prepareStatement("INSERT INTO SYS_TABLE_KEY(TABLE_NAME, TABLE_KEY_MAX) VALUES(?, ?)", java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
                preStat2.setString(1, tableName);
                preStat2.setInt(2, maxId);
                preStat2.executeUpdate();
            } else {
            }
          }
          dbConn.commit();
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException("errors.framework.get_next_seq", e, tableName);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { rs1.close(); } catch (Exception ignore) {} finally { rs1 = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { preStat1.close(); } catch (Exception ignore) {} finally { preStat1 = null; }
        try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
      }
  }
  /*
   * Update Code End
   */

  /* (non-Javadoc)
   * @see com.dcivision.framework.web.AbstractMaintAction#deleteRecord(org.apache.struts.action.ActionMapping, com.dcivision.framework.web.AbstractActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */

  
  public void deleteRecord(ActionMapping mapping, AbstractActionForm form,
      HttpServletRequest request, HttpServletResponse response)
      throws ApplicationException {
      AbstractDAObject obj = getMajorDAObject(request);
      try {
        AbstractSetupOptionDAObject setupOptionDAO = (AbstractSetupOptionDAObject) obj;
        SetupOption setupOption=(SetupOption) form.getFormData();
        if("SetupOptionDocumentRelationship".equals(request.getParameter("optionsSetupName"))){
          SetupOptionDocumentRelationshipDAObject setupOptionDocumentDAO = (SetupOptionDocumentRelationshipDAObject) setupOptionDAO;
          if(!setupOptionDocumentDAO.deleteObjectByNotUsed(setupOption)){
            addError(request,"errors.system.Relationship_is_used");
            throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR);
          }
        }else{
          setupOption = (SetupOption) setupOptionDAO.deleteObject(form.getFormData());
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      }
      return;
    }


  /* (non-Javadoc)
   * @see com.dcivision.framework.web.AbstractAction#getMajorDAObject(javax.servlet.http.HttpServletRequest)
   */
  
  protected AbstractDAObject getMajorDAObject(HttpServletRequest request)
    throws ApplicationException {

    //log.debug("DEBUG - MaintOptionsSetupAction.getMajorDAObject()");
    //log.debug("optionsSetupName: " + request.getParameter("optionsSetupName"));

    String setupOptionDAOName = SetupOptionFactory.getDAObjectName(request.getParameter("optionsSetupName"));
    try {
      AbstractSetupOptionDAObject setupOptionDAO =
        (AbstractSetupOptionDAObject) Class.forName(setupOptionDAOName).newInstance();
      setupOptionDAO.setDbConn(this.getConnection(request));
      setupOptionDAO.setSessionContainer(this.getSessionContainer(request));

      //log.debug("setupOptionDAOName: " + setupOptionDAOName);

      return setupOptionDAO;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
    }
  }

}
